package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.vo.excel.ExcelModelVO;
import com.bifang.module.base.common.vo.excel.ExcelReadVO;
import com.bifang.module.base.common.vo.excel.ExcelVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationCurVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationPeriodVO;
import com.bifang.module.base.core.helper.ApiContainer;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.bifang.module.system.core.dao.service.SysDictService;
import com.bifang.module.system.core.integration.impl.ExcelIntegrationImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.vo.eduLotteryAnnouncement.EduLotteryAnnouncementKeyVO;
import com.jwsoft.manager.common.vo.eduLotteryAnnouncementDetail.EduLotteryAnnouncementDetailKeyVO;
import com.jwsoft.manager.common.vo.eduLotteryAnnouncementDetail.EduLotteryAnnouncementDetailQueryVO;
import com.jwsoft.manager.common.vo.eduLotteryAnnouncementDetail.EduLotteryAnnouncementDetailVO;
import com.jwsoft.manager.core.dao.model.EduLotteryAnnouncementDetail;
import com.jwsoft.manager.core.dao.model.EduSchool;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.model.EduStudentEnrollKindergarten;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduLotteryAnnouncementDetailIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.integration.eduAddressTree.EduAddressTreeIntegration;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 金华摇号结果公示详情业务实现类
 *
 * @author wangt
 * @since 2024-06-16
 */
@ApiService(funcCode = "eduLotteryAnnouncementDetail", title = "金华摇号结果公示详情")
public class EduLotteryAnnouncementDetailIntegrationImpl implements EduLotteryAnnouncementDetailIntegration {

    @Autowired
    public EduLotteryAnnouncementDetailService eduLotteryAnnouncementDetailService;

    @Autowired
    public EduStudentEnrollPreIntegrationImpl eduStudentEnrollPreIntegration;

    @Autowired
    ExcelCommonHelper excelCommonHelper;

    @Resource
    private ApiContainer apiContainer;

    @Resource
    OperationPeriodIntegration operationPeriodIntegration;

    @Autowired
    OperationCacheIntegration operationCacheIntegration;

    @Autowired
    public DictHelper dictHelper;

    @Autowired
    public EduSchoolService eduSchoolService;

    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private RedisHelper redisHelper;

    public static final String REDIS_YHDR = "YWMBAPPLY:AnnouncementDetail:";

    @Autowired
    public ExcelIntegrationImpl excelIntegration;
    @Autowired
    EduAddressTreeIntegration eduAddressTreeIntegration;

    @Autowired
    EduAddressTreeOriginalService originalService;


    @Autowired
    SysDictService sysDictService;

    @Value("${spring.servlet.multipart.location}")
    private String tempPath;

    @Autowired
    EduStudentEnrollKindergartenService eduStudentEnrollKindergartenService;


    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0001", title = "金华摇号结果公示详情分页查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduLotteryAnnouncementDetailVO> getList(EduLotteryAnnouncementDetailQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        LambdaQueryWrapper<EduLotteryAnnouncementDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtil.isNotBlank(vo.getApplyId()),EduLotteryAnnouncementDetail::getApplyId,vo.getApplyId())
                .eq(StringUtil.isNotBlank(vo.getSchoolId()),EduLotteryAnnouncementDetail::getSchoolId,vo.getSchoolId())
                .eq(vo.getLotteryAnnouncementId()!=null,EduLotteryAnnouncementDetail::getLotteryAnnouncementId,vo.getLotteryAnnouncementId())
                .orderByDesc(EduLotteryAnnouncementDetail::getYear,EduLotteryAnnouncementDetail::getSchoolId).orderByAsc(EduLotteryAnnouncementDetail::getSerialNum);
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<EduLotteryAnnouncementDetail> list = eduLotteryAnnouncementDetailService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduLotteryAnnouncementDetail> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduLotteryAnnouncementDetailVO> resultList = Convert.toList(EduLotteryAnnouncementDetailVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0002", title = "金华摇号结果公示详情根据主键查询详情", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduLotteryAnnouncementDetailVO getById(EduLotteryAnnouncementDetailKeyVO vo) {
        EduLotteryAnnouncementDetail entity = eduLotteryAnnouncementDetailService.getById(vo.getLotteryAnnouncementDetailId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduLotteryAnnouncementDetailVO result = Convert.convert(EduLotteryAnnouncementDetailVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0003", title = "金华摇号结果公示详情保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduLotteryAnnouncementDetailVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0004", title = "金华摇号结果公示详情新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduLotteryAnnouncementDetail0004",
            operationName = "金华摇号结果公示详情新增",
            dataType = "lotteryAnnouncementDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduLotteryAnnouncementDetailVO add(EduLotteryAnnouncementDetailVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduLotteryAnnouncementDetail entity = Convert.convert(EduLotteryAnnouncementDetail.class, vo);
        eduLotteryAnnouncementDetailService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setLotteryAnnouncementDetailId(entity.getLotteryAnnouncementDetailId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0005", title = "金华摇号结果公示详情修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduLotteryAnnouncementDetail0005",
            operationName = "金华摇号结果公示详情修改",
            dataType = "lotteryAnnouncementDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduLotteryAnnouncementDetailVO edit(EduLotteryAnnouncementDetailVO vo) {
        if (ObjectUtils.isEmpty(vo.getLotteryAnnouncementDetailId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduLotteryAnnouncementDetail oldEntity = eduLotteryAnnouncementDetailService.getById(vo.getLotteryAnnouncementDetailId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduLotteryAnnouncementDetail entity = Convert.convert(EduLotteryAnnouncementDetail.class, vo);
        eduLotteryAnnouncementDetailService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0006", title = "金华摇号结果公示详情根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduLotteryAnnouncementDetail0006",
            operationName = "金华摇号结果公示详情删除",
            dataType = "lotteryAnnouncementDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduLotteryAnnouncementDetailKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getLotteryAnnouncementDetailId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduLotteryAnnouncementDetail entity = eduLotteryAnnouncementDetailService.getById(vo.getLotteryAnnouncementDetailId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduLotteryAnnouncementDetailService.removeById(vo.getLotteryAnnouncementDetailId());
    }

    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0007", title = "根据摇号结果公告id查询名单", funcType = FuncTypeEnum.query,publicFlag = BoolEnum.TRUE)
    public List<EduLotteryAnnouncementDetailVO> getListById(EduLotteryAnnouncementKeyVO vo) {
        LambdaQueryWrapper<EduLotteryAnnouncementDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduLotteryAnnouncementDetail::getLotteryAnnouncementId,vo.getLotteryAnnouncementId())
                .orderByAsc(EduLotteryAnnouncementDetail::getSerialNum);
        List<EduLotteryAnnouncementDetail> list = eduLotteryAnnouncementDetailService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<EduLotteryAnnouncementDetailVO> resultList = Convert.toList(EduLotteryAnnouncementDetailVO.class, list);
        return resultList;
    }

    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0008", title = "摇号结果公示导入", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduLotteryAnnouncementDetail0008",
            operationName = "摇号结果公示导入",
            dataType = "lotteryAnnouncementDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public ExcelReadVO readExcel(ExcelVO vo, MultipartFile file, EduLotteryAnnouncementDetailQueryVO queryVO) {
        ExcelReadVO excelReadVO = new ExcelReadVO();
        excelReadVO.setCount(0);
        ExcelModelVO excelModelVO = eduStudentEnrollPreIntegration.getModel(vo);
        InputStream in = null;
        String schoolId = queryVO.getSchoolId();
        EduSchool eduSchool = eduSchoolService.getById(schoolId);
        if (eduSchool == null) {
            throw new AppException("请先选择学校");
        }
        try {
            in = file.getInputStream();

            if (StringUtils.isBlank(excelModelVO.getReadClass())) {
                List<Map<String, Object>> list = excelCommonHelper.readExcel(excelModelVO, in, true);
                JSONArray jsonArray = new JSONArray();
                jsonArray.addAll(list);
                List<EduLotteryAnnouncementDetailVO> detailVOList2 = jsonArray.toJavaList(EduLotteryAnnouncementDetailVO.class);
                List<EduLotteryAnnouncementDetailVO> detailVOList = new ArrayList<>();
                //捆绑摇号
                for (EduLotteryAnnouncementDetailVO detailVO : detailVOList2) {
                    if(detailVO.getApplyId().contains(",")){
                        String[] applyIdArray = detailVO.getApplyId().split(",");
                        String[] fullNameArray ;
                        String[] idCardArray ;
                        if(SchoolCategoryEnum.KINDERGARTEN.getType().equals(eduSchool.getSchoolCategory())){
                             if(StringUtils.isNotBlank(detailVO.getChildFullNameTm())){
                                 fullNameArray = detailVO.getChildFullNameTm().split(",");
                             }else{
                                 fullNameArray = detailVO.getFullNameTm().split(",");
                             }
                            if(StringUtils.isNotBlank(detailVO.getChildIdcardTm())) {
                                idCardArray = detailVO.getChildIdcardTm().split(",");
                            }else{
                                idCardArray = detailVO.getIdcardTm().split(",");
                            }

                        }else {
                            if(StringUtils.isNotBlank(detailVO.getFullNameTm())) {
                                fullNameArray = detailVO.getFullNameTm().split(",");
                            }else{
                                fullNameArray = detailVO.getChildFullNameTm().split(",");
                            }
                            if(StringUtils.isNotBlank(detailVO.getIdcardTm())) {
                                idCardArray = detailVO.getIdcardTm().split(",");
                            }else{
                                idCardArray = detailVO.getChildIdcardTm().split(",");
                            }
                        }
                        for (int i = 0; i < applyIdArray.length; i++) {
                            EduLotteryAnnouncementDetailVO lottery = new EduLotteryAnnouncementDetailVO();
                            lottery.setApplyId(applyIdArray[i]);
                            lottery.setFullNameTm((fullNameArray[i]));
                            lottery.setIdcardTm((idCardArray[i]));
                            lottery.setSerialNum(detailVO.getSerialNum());
                            detailVOList.add(lottery);
                        }
                    }else {
                        detailVO.setFullNameTm(detailVO.getChildFullNameTm());
                        detailVO.setIdcardTm(detailVO.getChildIdcardTm());
                        detailVOList.add(detailVO);
                    }
                }

                //过滤报名编号为空数据
                detailVOList=detailVOList.stream()
                        .filter(
                                filterItem ->StringUtils.isNotBlank(filterItem.getApplyId()))
                        .collect(Collectors.toList());
                List<Map<String, Object>> successList = new ArrayList<>();
                List<Map<String, Object>> errorList = new ArrayList<>();

                String redisKey=REDIS_YHDR+schoolId;
                if(redisHelper.hasKey(redisKey)){
                   // throw new AppException("上一次导入正在处理中，不能导入");
                }else{
                    redisHelper.set(redisKey,"1",300);
                }

                for (EduLotteryAnnouncementDetailVO lotteryDetail : detailVOList) {
//                    if (lotteryDetail.getIdcardTm() == null || lotteryDetail.getFullNameTm() == null) {
//                        throw new AppException("模板有误!");
//                    }
                    String remarks = "";
                    boolean flag = false;


                    // 校验数据是否存在
                    int year = 0;
                    OperationCurVO curVO = new OperationCurVO();
                    curVO.setOperating("XN");
                    OperationPeriodVO operationPeriodVO =
                            operationPeriodIntegration.getCurrentByOperating(curVO);
                    if (operationPeriodVO != null) {
                        year = operationPeriodVO.getPeriodYear();
                    } else {
                        year = DateUtil.thisYear();
                    }
                    QueryWrapper<EduLotteryAnnouncementDetail> appointStudentQueryWrapper =
                            new QueryWrapper<>();
                    appointStudentQueryWrapper
                            .lambda()
                            .eq(EduLotteryAnnouncementDetail::getApplyId, lotteryDetail.getApplyId())
                            .eq(EduLotteryAnnouncementDetail::getSchoolId,schoolId)
                            .eq(EduLotteryAnnouncementDetail::getYear, year);
                    long count = eduLotteryAnnouncementDetailService.count(appointStudentQueryWrapper);
                    if (count > 0) {
                        flag = true;
                        remarks = "该报名号码信息已导入";
                    }

                    if(SchoolCategoryEnum.KINDERGARTEN.getType().equals(eduSchool.getSchoolCategory())){
                        QueryWrapper<EduStudentEnrollKindergarten> studentEnrollKindergartenQueryWrapper =  new QueryWrapper<>();
                        studentEnrollKindergartenQueryWrapper
                                .lambda()
                                .eq(EduStudentEnrollKindergarten::getApplyId, lotteryDetail.getApplyId())
                                .eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                                .eq(EduStudentEnrollKindergarten::getYear, year);
                        long enrollCount = eduStudentEnrollKindergartenService.count(studentEnrollKindergartenQueryWrapper);
                        if (enrollCount ==  0) {
                            flag = true;
                            remarks = "该报名号码不存在";
                        }
                    }else {
                        QueryWrapper<EduStudentEnroll> studentEnrollQueryWrapper =
                                new QueryWrapper<>();
                        studentEnrollQueryWrapper
                                .lambda()
                                .eq(EduStudentEnroll::getApplyId, lotteryDetail.getApplyId())
                                .eq(EduStudentEnroll::getSchoolId,schoolId)
                                .eq(EduStudentEnroll::getYear, year);
                        long enrollCount = eduStudentEnrollService.count(studentEnrollQueryWrapper);
                        if (enrollCount ==  0) {
                            flag = true;
                            remarks = "该报名号码不存在";
                        }
                    }


                    if (flag) {
                        lotteryDetail.setRemarks(remarks);
                        lotteryDetail.setYear(year);
                        errorList.add(JSON.parseObject(JSON.toJSONString(lotteryDetail), Map.class));
                    } else {
                        // 保存表信息
                        QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(EduStudentEnroll::getApplyId,lotteryDetail.getApplyId());
                        List<EduStudentEnroll> enrollList = eduStudentEnrollService.list(queryWrapper);
                        EduLotteryAnnouncementDetail detail = new EduLotteryAnnouncementDetail();
                        if(!CollectionUtils.isEmpty(enrollList)){
                            EduStudentEnroll enroll = enrollList.get(0);
                            detail.setAspirationType(enroll.getAspirationType());
                            detail.setSchoolCategory(enroll.getSchoolCategory());
                            detail.setSchoolNature(enroll.getSchoolNature());
                            detail.setYear(year);
                            detail.setConfigTypeName(enroll.getConfigTypeName());
                            detail.setConfigName(enroll.getConfigName());
                        }



                        detail.setLotteryAnnouncementId(queryVO.getLotteryAnnouncementId());
                        detail.setApplyId(lotteryDetail.getApplyId());
                        detail.setIdcardTm(getIdcard(lotteryDetail.getIdcardTm()));
                        detail.setFullNameTm(getFullName(lotteryDetail.getFullNameTm()));
                        detail.setSerialNum(lotteryDetail.getSerialNum());
                        detail.setSchoolId(queryVO.getSchoolId());
                        detail.setSchoolName(queryVO.getSchoolName());


                        eduLotteryAnnouncementDetailService.save(detail);

                        successList.add(JSON.parseObject(JSON.toJSONString(lotteryDetail), Map.class));
                    }

                }
                excelReadVO.setCount(successList.size() + errorList.size());
                excelReadVO.setSuccessCount(successList.size());
                excelReadVO.setSuccessList(successList);
                excelReadVO.setErrorList(errorList);
                excelReadVO.setErrorCount(errorList.size());
                redisHelper.del(redisKey);



            }else {
                // 使用funcCode读取
                //本地接口
                ApiModel apiModel = apiContainer.get(excelModelVO.getReadClass());
                if (apiModel != null) {
                    Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
                    if (null != bean) {
                        Object result = apiModel.getMethod().invoke(bean, vo, file);
                        return (ExcelReadVO) result;
                    }
                }
                //todo 微服务接口
            }
        } catch (AppException appEx) {
            throw appEx;
        } catch (IOException e) {
            throw new AppException("读取文件异常:" + e.getMessage());
        } catch (IllegalAccessException e) {
            throw new AppException("调用自定义读取服务异常:" + e.getMessage());
        } catch (InvocationTargetException e) {
            throw new AppException("调用自定义读取服务异常:" + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return excelReadVO;
    }

    @Override
    @OpApi(funcCode = "eduLotteryAnnouncementDetail0009", title = "摇号公示数据导出", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void exportInfo(EduLotteryAnnouncementDetailQueryVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO = excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum = 1;
        setData(excelModelVO, null, destFilePath, vo, pageNum);
        String fileName = vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }
    }


    private void setData(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduLotteryAnnouncementDetailQueryVO vo, int pageNum) {
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag = false;
        try {
            PageInfo<EduLotteryAnnouncementDetailVO> pageInfo = getList(vo);
            String total = String.valueOf(pageInfo.getTotal());
            List<Object> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(pageInfo.getList())) {
                for (EduLotteryAnnouncementDetailVO detailVO : pageInfo.getList()) {
                    list.add(detailVO);
                }
            }
            if (pageNum == 1) {
                if (excelWriter == null) {
                    excelWriter = excelCommonHelper.createExcelWriter(excelModelVO, destFilePath, Integer.parseInt(total));
                }
                excelCommonHelper.writeBean(excelWriter, list);
            } else {
                excelCommonHelper.writeBean(excelWriter, list);
            }
            if (pageInfo.isHasNextPage()) {
                pageNum = pageNum + 1;
                setData(excelModelVO, excelWriter, destFilePath, vo, pageNum);
            } else {
                closeFlag = true;
            }
        } catch (AppException appEx) {
            throw appEx;
        } catch (Exception e) {
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        } finally {
            if (closeFlag && excelWriter != null) {
                excelWriter.close();
            }
        }
    }

    private String getFullName(String str) {
        if (StringUtils.isBlank(str)) {
            return str;
        }
        if (str.length() < 3) {
            return str.substring(0, 1) + "*";
        } else {
            int le = str.length() - 1;
            return str.substring(0, 1) + "*" + str.substring(le);
        }

    }
    //证件号码脱敏
    private String getIdcard(String str){
        if(StringUtils.isBlank(str)){
            return str;
        }
        if (str.length()==18) {
            return str.substring(0,6)+"********"+str.substring(14,18);
        }else{
            int len=str.length();
            String  enCard=str.substring(0, 2);
            for(int i=0;i<len-4;i++){
                enCard=enCard+"*";
            }
            enCard=enCard+str.substring(len-3);
            return enCard;
        }
    }

}
